﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace BtLibs
{
    public static class HtmlUtility
    {
        public static HtmlNode Load(string file)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.Load(file);
            return Root(doc);
        }
        public static HtmlNode LoadHtml(string content)
        {
            HtmlDocument doc = new HtmlDocument();
            if (!string.IsNullOrEmpty(content))
            { doc.LoadHtml(content); }
            return Root(doc);
        }
        private static HtmlNode Root(HtmlDocument doc)
        {
            if (doc == null) { return null; }
            HtmlNode docNode = doc.DocumentNode;
            if (docNode == null) { return null; }
            if (docNode.ChildNodes.Count == 0) { return doc.CreateElement("root"); }
            else { return docNode.ChildNodes[0]; }
        }
        public static void ReplaceChild(HtmlNode newNode, HtmlNode oldNode)
        {
            if (newNode == null || oldNode == null) { return; }
            oldNode.ParentNode.ReplaceChild(newNode, oldNode);
        }
        public static void RemoveNodes(HtmlNode node, string xpath)
        {
            if (node == null) { return; }
            HtmlNodeCollection childs = node.SelectNodes(xpath);
            if (childs != null)
            {
                foreach (HtmlNode child in childs)
                {
                    child.Remove();
                }
            }
        }
        public static void RemoveNodeAttributes(HtmlNode node, string xpath)
        {
            if (node == null) { return; }
            HtmlNodeCollection childs = node.SelectNodes(xpath);
            if (childs != null)
            {
                foreach (HtmlNode child in childs)
                {
                    child.Attributes.RemoveAll();
                }
            }
        }
    }
}
